package main

import (
	"bytes"
	"fmt"
	"net"
	"runtime"

	"gitcode.com/shexk/naserver/core"
	"gitcode.com/shexk/naserver/files"

	x "gitee.com/shexk/gtl/net"
	"gitee.com/shexk/gtl/protocol"
)

func main() {
	wait := make(chan int, 100)

	var targetDir = ""
	switch runtime.GOOS {
	case "darwin":
		targetDir = "/Volumes/MyData"
	case "windows":
		targetDir = "d:\\Application"
	}

	if core.GetConfig().LoadConfig() != nil {
		core.GetConfig().MainDir = targetDir
		core.GetConfig().DownBlockSize = 1460
		core.GetConfig().TCPPacketSize = 1460
		core.GetConfig().ServerPort = 3000
		if err := core.GetConfig().SaveConfig(); err != nil {
			fmt.Println("Save Config Error:", err)
			return
		}
	}

	server := x.NewTcpServer()
	server.OnEvent = func(conn net.Conn, state uint8, data []byte, datasize uint16, err error) {
		switch state {
		case x.TCP_STATE_CONNECTED:
			fmt.Println("Client Connect Addr:", conn.RemoteAddr().String())
		case x.TCP_STATE_DISCONNECTED:

		case x.TCP_STATE_DATA:
			cmd := data[0]
			switch cmd {
			case 0x01:
				{
					req := files.RequestCmd{}
					data = data[1:]
					protocol.GetStructFromBytes(data, &req)
					go func() {
						if req.Value == "" {
							bufs := bytes.NewBuffer(nil)
							bufs.WriteByte(0x03)
							buf := files.NewSearchFile(targetDir).GetDirInfo()
							bufs.Write(buf)
							x.WritePackage(conn, bufs.Bytes())
						} else {
							bufs := bytes.NewBuffer(nil)
							bufs.WriteByte(0x03)
							buf := files.NewSearchFile(req.Value).GetDirInfo()
							bufs.Write(buf)
							x.WritePackage(conn, bufs.Bytes())
						}
					}()
				}
			case 0x02:
				{
					req := files.RequestCmd{}
					data = data[1:]
					protocol.GetStructFromBytes(data, &req)
					go func() {
						files.DownloadFile(req.Value, conn)
					}()
				}
			}
		case x.TCP_STATE_ERROR:

		}
	}
	server.Start(60000)
	fmt.Println("Server Start Port=", core.GetConfig().ServerPort)

	<-wait
}

//Mac ../../bin/fyne package -os darwin -icon app.ico
//Win fyne package -os windows -icon app.ico
//linux fyne package -os linux -icon myapp.png
